package org.example.code;

import org.example.mapping.ServletMapping;
import org.example.mapping.ServletMappingConfig;
import org.example.server.MyRequest;
import org.example.server.MyResponse;
import org.example.servlet.MyServlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class MyTomcat {

    // 服务端口
    private int port = 8080;

    // 链接映射集合
    private Map<String, String> urlServletMap = new HashMap<>();

    public MyTomcat(int port) {
        this.port = port;
    }

    public void start () {
        // 初始化 URL与对应处理的servlet的关系
        initServletMapping();

        ServerSocket serverSocket = null;
        try {
            // Socket和ServerSocket是用于创建网络连接的重要类。Socket类用于创建客户端套接字，而ServerSocket类用于创建服务器套接字
            serverSocket = new ServerSocket(port);
            System.out.println("MyTomcat is start......");
            // 处理请求，直至全部完成
            while (true) {
                // 从连接请求队列中取出一个客户的连接请求，然后创建与客户连接的Socket对象，并将它返回。如果队列中没有连接请求，accept()方法就会一直等待，直到接收到了连接请求才返回。
                Socket socket = serverSocket.accept();
                // 输入流
                InputStream inputStream = socket.getInputStream();
                // 输出流
                OutputStream outputStream = socket.getOutputStream();

                MyRequest myRequest = new MyRequest(inputStream);
                MyResponse myResponse = new MyResponse(outputStream);

                // 请求分发
                dispatch(myRequest, myResponse);
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 初始化应用访问
     **/
    private void initServletMapping() {
        for (ServletMapping servletMapping : ServletMappingConfig.servletMappingList) {
            urlServletMap.put(servletMapping.getUrl(), servletMapping.getClazz());
        }
    }

    /**
     * 请求分发
     **/
    private void dispatch(MyRequest myRequest, MyResponse myResponse) {
        String clazz = urlServletMap.get(myRequest.getUrl());

        // 反射
        try {
            if (!Objects.isNull(clazz)) {
                Class<MyServlet> myServletClass = (Class<MyServlet>) Class.forName(clazz);
                MyServlet myServlet = myServletClass.newInstance();
                // 工厂模式
                myServlet.server(myRequest, myResponse);
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
}
